import React, { type ReactNode } from "react";
import type { CalendarProps } from ".";
import type { Dayjs } from "dayjs";

const weekList = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];

interface MonthCalenderProps extends CalendarProps {}

const getAllDays = (value: Dayjs) => {
  const startDate = value.startOf("month");
  const day = startDate.day();
  const daysInfo: Array<{ date: Dayjs; currentMonth: boolean }> = new Array(
    6 * 7
  );

  // 填充上个月的日期
  for (let i = 0; i < day; i++) {
    daysInfo[i] = {
      date: startDate.subtract(day - i, "day"),
      currentMonth: false,
    };
  }

  // 填充当前月和下个月的日期
  for (let i = day; i < daysInfo.length; i++) {
    const calcDate = startDate.add(i - day, "day");
    daysInfo[i] = {
      date: calcDate,
      currentMonth: calcDate.month() === value.month(),
    };
  }

  return daysInfo;
};

function renderDays(
  days: Array<{ date: Dayjs; currentMonth: boolean }>,
  dateRender: MonthCalenderProps["dateRender"],
  dateInnerContent: MonthCalenderProps["dateInnerContent"]
) {
  const rows = [];
  for (let i = 0; i < 6; i++) {
    const row = [];
    for (let j = 0; j < 7; j++) {
      const item = days[i * 7 + j];
      row.push(
        <div
          key={j}
          className="flex-1 border border-gray-200 p-2.5 text-center"
        >
          <span
            className={item.currentMonth ? "text-gray-900" : "text-gray-400"}
          >
            {dateRender ? dateRender(item.date) : item.date.date()}
          </span>
        </div>
      );
    }
    rows.push(
      <div key={i} className="flex h-[100px]">
        {row}
      </div>
    );
  }
  return rows;
}

const MonthCalender = (props: MonthCalenderProps) => {
  const allDays = getAllDays(props.value);
  const { dateRender, dateInnerContent } = props;

  return (
    <div className="font-sans">   
      <div className="flex w-full border-b border-b-gray-300">
        {weekList.map((day) => (
          <div
            key={day}
            className="flex-1 px-4 py-5 text-left text-gray-500 text-sm font-medium"
          >
            {day}
          </div>
        ))}
      </div>

      <div className="calendar-month-body">
        {renderDays(allDays, dateRender, dateInnerContent)}
      </div>
    </div>
  );
};

export default MonthCalender;
